package com.jsu.hotelmanagement.observerModel.thread;

import com.jsu.hotelmanagement.dao.RoomDao;
import com.jsu.hotelmanagement.observerModel.observer.RoomObserver;
import com.jsu.hotelmanagement.pojo.vo.CommonResult;
import com.jsu.hotelmanagement.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.DelayQueue;

/**
 * @author Mo__
 */
@Component
public class CheckOut implements Runnable{

    @Autowired
    RoomDao roomDao;

    @Autowired
    RoomService roomService;

    /**
     * 房间状态:
     * 0空闲,1已用,2已预定,3清理中, 4暂用
     */
    public static final int ROOM_VACANCY = 0;
    public static final int ROOM_USED = 1;
    public static final int ROOM_ORDERED = 2;
    public static final int ROOM_CLEANING = 3;
    public static final int ROOM_BANNED = 4;

    private DelayQueue<RoomObserver> roomObserverDelayQueue = new DelayQueue<>();

    public DelayQueue<RoomObserver> getRoomObserverDelayQueue() {
        return roomObserverDelayQueue;
    }

    public void setRoomObserverDelayQueue(DelayQueue<RoomObserver> roomObserverDelayQueue) {
        this.roomObserverDelayQueue = roomObserverDelayQueue;
    }


    @Override
    public void run() {
        List<RoomObserver> roomObserverList = roomDao.queryOrderInfo();
        roomObserverDelayQueue.addAll(roomObserverList);
        System.out.println("队头名字为："+roomObserverDelayQueue.peek()+"    队列长度为："+roomObserverDelayQueue.size());
        while(true){
            if(roomObserverDelayQueue.peek()!=null) {
//                System.out.println("System: "  + System.currentTimeMillis());
//                System.out.println("peek: " + roomObserverDelayQueue.peek().getEndTime().getTime());
                if (roomObserverDelayQueue.peek().getEndTime().getTime() < System.currentTimeMillis()) {
                    try {
                        //时间到了这里就会take到，不然就阻塞了，时间到了执行什么逻辑在下面写。
                        RoomObserver roomObserver = roomObserverDelayQueue.take();
                        //  退房更改房间状态
                        roomDao.updateRoomStatus(roomObserver.getRoomId(), ROOM_VACANCY);
                        CommonResult commonResult = roomService.guestCheckOut(roomObserver.getRoomId());
                        if (commonResult.getCode() != 200) {
                            System.err.println("错误");
                        } else {
                            System.out.println("成功退房");
                        }
                        System.out.println("roomId为->"+roomObserver.getRoomId()+"<-的房间自动退房");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

}
